<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
    <meta name="format-detection" content="telephone=no">
    <meta name="viewport" content="minimum-scale=1.0,maximum-scale=1,width=device-width,user-scalable=no"/>
    <title>WS测试</title>


</head>

<body>
<section class="nav">
    <div class="subNav">
        <div class="slipMarquee" id="stock">

        </div>
        <div>
            <input type="text" id="txt"/>
            <button value="send" onclick="send();">send</button>
        </div>
    </div>
</section>

<script language="javascript" type="text/javascript">
    window.WebSocket = window.WebSocket || window.MozWebSocket;
    var socket = new WebSocket("ws://localhost:8888/echo"); // 注意这里的ip地址改为你自己的地址，创建sockect客户端
    socket.binaryType='arraybuffer'
    socket.onopen = function () {
        socket.onclose = function (e) {// 关闭连接处理事件
            alert('close the socket');
        };

        socket.onerror = function (msg) {// 出错处理事件
            alert('error:' + msg.toLocaleString());
        };
    };


    socket.onmessage = function (e) {
        // 收到消息处理事件，将收到的内容显示在页面上
        document.getElementById('stock').innerHTML = '<font color =red>' +event.data + '</font>';
    };

    function send() {// 发送输入
        socket.send(document.getElementById('txt').value);
    }

    function byteToString(arr) {
        if(typeof arr === 'string') {
            return arr;
        }
        var str = '',
            _arr = arr;
        for(var i = 0; i < _arr.length; i++) {
            var one = _arr[i].toString(2),
                v = one.match(/^1+?(?=0)/);
            if(v && one.length == 8) {
                var bytesLength = v[0].length;
                var store = _arr[i].toString(2).slice(7 - bytesLength);
                for(var st = 1; st < bytesLength; st++) {
                    store += _arr[st + i].toString(2).slice(2);
                }
                str += String.fromCharCode(parseInt(store, 2));
                i += bytesLength - 1;
            } else {
                str += String.fromCharCode(_arr[i]);
            }
        }
        return str;
    }

</script>

</body>

</html>
